﻿//This filter is tested and seems to work correctly

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// this is used to extract a channel.
    /// u might also use
    /// new Lambda("c.R, 0, 0") to extract red channel for example
    /// </summary>
    public class RGBChannelExtract : BaseImageFilter
    {
        protected bool m_bR = true;
        protected bool m_bG = false;
        protected bool m_bB = false;

        /// <summary>
        /// default constructor
        /// </summary>
        public RGBChannelExtract()
        {
        }

        /// <summary>
        /// choose which channels to extract
        /// </summary>
        /// <param name="_r"></param>
        /// <param name="_g"></param>
        /// <param name="_b"></param>
        public RGBChannelExtract(bool _r, bool _g, bool _b)
        {
            m_bR = _r;
            m_bG = _g;
            m_bB = _b;
        }

        /// <summary>
        /// used by clone to create a deep copy
        /// </summary>
        /// <param name="_rgbChannelExtract"></param>
        internal RGBChannelExtract(RGBChannelExtract _rgbChannelExtract)
        {
            this.m_bR = _rgbChannelExtract.m_bR;
            this.m_bG = _rgbChannelExtract.m_bG;
            this.m_bB = _rgbChannelExtract.m_bB;
        }

        /// <summary>
        /// Extract the channel(s)
        /// </summary>
        /// <param name="_bitmap"></param>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;
            Color color = Color.Transparent;

            int y = 0;
            int x = 0;

            int nHeight = bitmap.Height;
            int nWidth = _bitmap.Width;

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    color = bitmap.GetPixel(x, y);
                    if (m_bR)
                    {
                        color = Color.FromArgb(0, color.G, color.B);
                    }
                    if (m_bG)
                    {
                        color = Color.FromArgb(color.R, 0, color.B);
                    }
                    if (m_bB)
                    {
                        color = Color.FromArgb(color.R, color.G, 0);
                    }
                    bitmap.SetPixel(x, y, color);
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// create a deep copy
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new RGBChannelExtract(this);
        }
    }
}
